package com.woniuxy.core.service.impl;

import com.woniuxy.core.mapper.OrderRunMapper;
import com.woniuxy.core.mapper.RunMapper;
import com.woniuxy.core.mapper.ShopOrderMapper;
import com.woniuxy.core.service.OrderRunService;
import com.woniuxy.entity.AllRun;
import com.woniuxy.entity.AllUser;
import com.woniuxy.entity.DTO.GrabEvent;
import com.woniuxy.entity.OrderRun;
import com.woniuxy.entity.ShopOrder;
import com.woniuxy.enums.ResponseEnum;
import com.woniuxy.util.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@Service
public class OrderRunServiceImpl implements OrderRunService {

    private static final Logger log = LoggerFactory.getLogger(OrderRunServiceImpl.class);
    @Autowired
    private RunMapper runMapper;
    @Autowired
    private OrderRunMapper orderRunMapper;
    @Autowired
    private ShopOrderMapper shopOrderMapper;

    private static final String ORDER_PREFIX = "ORD";
    //创建订单
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(GrabEvent grabEvent){
        //创建订单
        String runNumber = grabEvent.getTaskId();
        //获取帖子信息复制到订单里面
        AllRun runByRN = runMapper.getRunByRN(runNumber);
        ShopOrder shopOrder = new ShopOrder();

//        shopOrder.setOrderNumber(runNumber);
        shopOrder.setOrderNumber(OrderNumberGenerator());
        shopOrder.setUserId(runByRN.getUserId());//买家变成发布订单的人
        shopOrder.setSellerId(grabEvent.getUserId());//卖家变成接单的人
        shopOrder.setItemId(runByRN.getId());
        shopOrder.setTotalAmount(runByRN.getPrice());
        shopOrder.setStatus(1);
        shopOrder.setCreateTime(new Date());
        shopOrder.setUpdateTime(new Date());
        shopOrder.setAddress(runByRN.getEndaddress());
        shopOrder.setRunNumber(runNumber);
        System.out.println("shopOrder"+shopOrder);
        //存数据库
        shopOrderMapper.insert(shopOrder);
        log.info("订单信息",shopOrder);
        System.out.println("订单"+shopOrder);
        //更新跑腿帖子状态(跑腿人id、帖子状态)
        runMapper.updateRun(grabEvent.getUserId(),runNumber);
        System.out.println("run"+runByRN);
    }

    @Override
    public ShopOrder getOrderByRN(String runNumber) {
        return orderRunMapper.getOrderByRN(runNumber);
    }

    @Override
    public void updateStateToPay(String runNumber) {
        System.out.println("runNumber"+runNumber);
        orderRunMapper.updateStateToPay(runNumber);
    }

    public String OrderNumberGenerator(){
        // 生成UUID并截取部分字符（去掉横杠）
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
        // 组合订单号
        return ORDER_PREFIX + uuid;
    }
}
